<template>
	<div class="content-box add-creation">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<div class="el-form-sub-title">基本信息</div>
			<el-form-item label="内容类型" prop="type">
				<el-radio-group v-model="form.type" class="good-type">
					<el-radio :value="0"> 图文</el-radio>
					<el-radio :value="1"> 视频</el-radio>
					<el-radio :value="2"> 公众号文章</el-radio>
					<el-radio :value="3"> 视频号视频</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="内容分类" prop="contentTypeId">
				<RefreshSelect
					v-model="form.contentTypeId"
					:api="fetchTypeList"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select"
					link="/content/type"
				></RefreshSelect>
			</el-form-item>
			<el-form-item label="内容封面" prop="contentImage">
				<uploadImage v-model:file-list="form.contentImage" :limit="1" :fileSize="300 / 1024" packageName="content">
					<template #tip> 建议尺寸：800*800像素，300kb以下，支持PNG/JPG格式 </template>
				</uploadImage>
			</el-form-item>
			<!-- <el-form-item label="微信视频" prop="videoUrlWx" v-if="form.type == 1">
				<uploadVideo v-model:file-list="form.videoUrlWx" :limit="1" :fileSize="30" packageName="content">
					<template #tip packageName="content"> 视频大小不超过 30 MB，建议时长五分钟以内， 建议宽高比1：1或16:9， 视频文件格式建议：.mp4</template>
				</uploadVideo>
			</el-form-item> -->
			<el-form-item label="支付宝视频" prop="videoUrlAlipay" v-if="form.type == 1">
				<el-input v-model="form.videoUrlAlipay" placeholder="输入优酷视频链接" />
				<div class="el-upload__tip" style="width: 100%">
					<p>
						Step1.请使用小程序关联<a href="https://mp.youku.com/new/video" target="_block"
							><el-button style="vertical-align: baseline" link type="primary" size="small" @click="">支付宝优酷账号上传视频</el-button></a
						>并获得视频码
					</p>
					<p>Step2.复制并将视频码链接进行输入(示例：XNjM4MTk0NTkyMA==)</p>
				</div>
			</el-form-item>
			<el-form-item label="内容标题" prop="contentTitle">
				<el-input v-model="form.contentTitle" :maxlength="50" placeholder="输入内容标题(少于50字)" />
			</el-form-item>
			<el-form-item label="投放渠道" prop="target">
				<el-checkbox-group v-model="form.target">
					<el-checkbox :label="1" :value="1" v-if="[0, 1].includes(form.type)">支付宝小程序</el-checkbox>
					<el-checkbox :label="0" :value="0">微信小程序</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="内容推荐" prop="recommended">
				<el-radio-group v-model="form.recommended" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">内容设为推荐将在小程序首页进行推广展示</p>
			</el-form-item>
			<el-form-item label="内容排序">
				<el-input-number
					@blur="
						() => {
							form.order = form.order || 0;
						}
					"
					class="num-left"
					:min="0"
					:max="999999999"
					:controls="false"
					placeholder="输入排序(默认0，越大越靠前)"
					v-model="form.order"
				/>
			</el-form-item>
			<el-form-item label="起始浏览量" prop="start">
				<el-input-number
					@blur="
						() => {
							form.start = form.start || 0;
						}
					"
					class="num-left"
					:min="0"
					:max="999999999"
					:controls="false"
					placeholder="输入起始浏览量(默认0)"
					v-model="form.start"
				/>
			</el-form-item>
			<el-form-item label="文章链接" prop="outUrl" v-if="form.type == 2">
				<el-input placeholder="输入文章链接" v-model="form.outUrl" />
			</el-form-item>
			<el-form-item label="视频ID" prop="videoID" v-if="form.type == 3">
				<el-input placeholder="输入视频ID" v-model="form.videoID" />
			</el-form-item>
			<el-form-item label="内容详情" v-if="form.type == 0" prop="contentInfo">
				<Editor v-model="form.contentInfo"></Editor>
			</el-form-item>

			<div class="el-form-sub-title" v-if="[0, 1].includes(form.type)">关联推荐</div>

			<el-form-item prop="product" v-if="[0, 1].includes(form.type)">
				<el-button type="primary" link class="mt-20 mb20" @click="openAddGood">+ 选择商品</el-button>
				<el-table class="form-table" :data="form.product">
					<el-table-column label="商品ID" prop="id" width="200" align="center"> </el-table-column>
					<el-table-column label="商品名称" prop="productUrl" align="center">
						<template #default="scope">
							<div class="flex-center">
								<el-image class="flex-shrink" :src="scope.row.productImage" style="width: 50px; height: 50px"></el-image>
								<div class="ml10" style="text-align: left">
									<div>{{ scope.row.productName }}</div>
									<div>{{ scope.row.productCode }}</div>
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template #default="scope">
							<el-button type="primary" link @click="delDetailItem(scope)"> 移除 </el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="() => onSubmit(1)" plain>立即发布</el-button>
					<el-button type="primary" v-debounce="() => onSubmit(0)">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
		<AddItem :visible="updateVisible" @handleClose="handleClose"></AddItem>
	</div>
</template>

<script setup lang="tsx" name="addGood">
import { ref, reactive, onBeforeMount, onMounted } from 'vue';
import { ElMessage, type FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import dayjs from 'dayjs';
import uploadImage from '/@/components/upload/image.vue';
import uploadVideo from '/@/components/upload/video.vue';
import Editor from '/@/components/myEditor/index.vue';
import RefreshSelect from '/@/components/refreshSelect/index.vue';
import { fetchTypeList, fetchCreationDetail, fetchCreateCreation, fetchUpdateCreation } from '/@/api/content';
import AddItem from './dialog/addItem.vue';
const route = useRoute();
const router = useRouter();
const formRef = ref();
const form = ref<any>({
	type: 0,
	contentImage: [],
	product: [],
	target: [],
	videoUrlWx: [],
	videoUrlAlipay: '',
	order: 0,
	start: 0,
});
//校验规则
const rules = reactive<FormRules<any>>({
	type: [{ required: true, trigger: 'blur', message: '内容类型不能为空' }],
	contentTypeId: [{ required: true, trigger: 'blur', message: '内容分类不能为空' }],
	contentImage: [{ required: true, message: '内容封面不能为空', trigger: ['change', 'blur'] }],
	contentTitle: [{ required: true, message: '内容标题不能为空', trigger: ['change', 'blur'] }],
	target: [{ required: true, message: '投放渠道不能为空', trigger: ['change', 'blur'] }],
	outUrl: [{ required: true, message: '文章链接不能为空', trigger: ['change', 'blur'] }],
	videoID: [{ required: true, message: '视频ID不能为空', trigger: ['change', 'blur'] }],
	contentInfo: [{ required: true, message: '内容详情不能为空', trigger: ['change', 'blur'] }],
});

const updateVisible = ref(false);
const editId = ref();

const openAddGood = () => {
	updateVisible.value = true;
};

const formatParams = (data: any) => {
	return {
		...data,
		contentImage: data.contentImage ? data.contentImage.map((item: any) => item.url).join() : '',
		videoUrlWx: data.videoUrlWx && data.videoUrlWx.map((item: any) => item.url).join(),
		productId: data.product && data.product.map((item: any) => item.id).join(),
		target: data.target.join(),
		outUrl: data.outUrl || data.videoID,
	};
};

const onSubmit = async (status: any) => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = formatParams(form.value);
			params.status = status;
			if (form.value.type == 3) {
				params.outUrl = form.value.videoID;
			}

			const res = editId.value ? await fetchUpdateCreation(params) : await fetchCreateCreation(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑成功' : '新增成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/content/creation');
};
const handleClose = (data: any) => {
	updateVisible.value = false;
	if (data) {
		data.forEach((item: any) => {
			const has = form.value.product.some((v: any) => v.id == item.id);
			if (!has) {
				form.value.product.push(item);
			}
		});
	}
};
const delDetailItem = (scope: any) => {
	form.value.product.splice(scope.$index, 1);
};

onMounted(async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const res = await fetchCreationDetail({ id: editId.value });
		if (res.code === 200) {
			const data = res.data;
			data.contentImage = data.contentImage.split(',').map((item: any) => {
				return {
					url: item,
				};
			});
			data.contentTypeId = data.contentType.id;
			data.product = data.products || [];
			data.recommended = data.recommended ? 1 : 0;
			data.target = data.target.split(',').map((v) => Number(v));
			if (data.type == 3) {
				data.videoID = data.outUrl;
			}
			data.videoUrlWx = data.videoUrlWx
				? data.videoUrlWx.split(',').map((item: any) => {
						return {
							url: item,
						};
					})
				: [];

			form.value = data;
		}
	}
});
</script>

<style scoped lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number {
			max-width: 450px;
		}
	}
}
</style>
<style lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-input-number,
		.el-select,
		.refresh-select-wrapper {
			width: 100%;
			max-width: 450px;
		}
	}
}
</style>
